package com.xiaoyao.novel.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.xiaoyao.novel.service.WebInfoService;

/**
 * 不能直接访问JSP. JSP 过滤器,编码过滤器.第一层filter
 * 
 * @author 旷明爱
 * @date Dec 13, 2012 9:13:38 AM
 */
public class JSPFilter implements Filter {
	private static Logger logger = Logger.getLogger(JSPFilter.class);
	static WebInfoService webInfoService=new WebInfoService();
	
	public static final int CACHE_SECOND=30*60 ;// 秒数,30分钟
	public static final int CACHE_MS=CACHE_SECOND*1000 ;
	 
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 编码过滤器.统一设置.
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setHeader("Connection", "keep-alive");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uri = httpRequest.getRequestURI();
//		// ///域名跳转 
		String serverName = request.getServerName();//serverName:tianfengfeiye.com
		String userAgent = httpRequest.getHeader("User-agent"); // Baiduspider
		// 获取IP
		String ip = "";
		if (httpRequest.getHeader("x-forwarded-for") == null) {
			ip = httpRequest.getRemoteAddr();
		} else {
			ip = httpRequest.getHeader("x-forwarded-for");
		}
		if ("182.118.33.6".equals(ip)) {
			logger.warn( "问题IP:URI:"+uri +",serverName:"+serverName+",ip:"+ip) ;
			return;
		}
		 
		logger.info( "URI:"+uri +",serverName:"+serverName+",ip:"+ip) ;
		if (!uri.contains("system") ) {
			httpResponse.setHeader("Cache-Control", "max-age="+CACHE_SECOND);
		}
//		// ///域名跳转//暂时不做判断
//		String serverName = request.getServerName();//serverName:tianfengfeiye.com
//		String userAgent = httpRequest.getHeader("User-agent"); // Baiduspider
//		logger.debug( "userAgent:" + userAgent+",serverName:"+serverName);
//		WebInfo webInfo=webInfoService.getStaticWebInfo();
//		if( (webInfo.getStrict() &&  !webInfo.getDomain().replaceAll(".+//", "") .equals( serverName)) //// 必须和域名一致,包括www
//			||(!webInfo.getStrict()&& !serverName.contains(  webInfo.getDomain().replaceAll(".+//www.", "") ))){
//			String url =webInfo.getDomain() + uri; 
//			httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);// 301
//			httpResponse.setHeader("Location", url); 
//			return; 
//		} 
		//首页判断.
		try {
			chain.doFilter(request, response);
		} catch (Throwable e) { 
			logger.error("JSP过滤器错误:"+e+",URI:"+uri);
		}
	}

	public void destroy() {
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
}